package cn.akwangl.spring.dependency.inject;

import cn.akwangl.spring.dependency.inject.model.UserHolder;
import cn.akwangl.spring.ioc.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;

/**
 * Java 注解字段注入
 *
 * @author youyongkun
 * @date 2021/7/18 10:34 上午
 */
public class AnnotationDependencyFieldInjectionDemo {

    // @Autowired 会忽略掉静态字段
    @Autowired
    public
    //    static
            UserHolder userHolder;

    @Resource
    private UserHolder userHolder2;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册配置类
        applicationContext.register(AnnotationDependencyFieldInjectionDemo.class);
        // 读取XML BeanDefinition
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
        String location = "classpath:/META-INF/dependency-lookup-context.xml";
        xmlReader.loadBeanDefinitions(location);
        // 刷新上下文
        applicationContext.refresh();

        AnnotationDependencyFieldInjectionDemo fieldInjectionDemo = applicationContext.getBean(AnnotationDependencyFieldInjectionDemo.class);

        System.out.println(fieldInjectionDemo.userHolder);
        System.out.println(fieldInjectionDemo.userHolder2);

        System.out.printf("userHolder 是否与 userHolder2 相等: %s \n", fieldInjectionDemo.userHolder == fieldInjectionDemo.userHolder2);

        // 关闭容器
        applicationContext.close();
    }

    @Bean
    public UserHolder userHolder(User user) {
        UserHolder userHolder = new UserHolder();
        userHolder.setUser(user);
        return userHolder;
    }
}
